﻿using Dapr;
using Dapr.Client;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace FrontEnd.Controllers
{
    [Route("FrontEnd/[controller]")]
    [ApiController]
    public class PubSubController : ControllerBase
    {
        private readonly ILogger<PubSubController> _logger;
        private readonly DaprClient _daprClient;
        public PubSubController(ILogger<PubSubController> logger, DaprClient daprClient)
        {
            _logger = logger;
            _daprClient = daprClient;
        }
        const string PUB_SUN = "rabbitmq-pubsub";
        const string TOPIC_NAME = "test_topic_code";
        [HttpGet("pub_code")]
        public async Task<ActionResult> PubCodeAsync()
        {
            var data = new WeatherForecast();
            await _daprClient.PublishEventAsync<WeatherForecast>(PUB_SUN, TOPIC_NAME, data);
            return Ok();
        }
        [Topic(PUB_SUN, TOPIC_NAME)]
        [HttpPost("sub_code")]
        public async Task<ActionResult> SubCode()
        {
            Stream stream = Request.Body;
            byte[] buffer = new byte[Request.ContentLength.Value];
            stream.Position = 0L;
            await stream.ReadAsync(buffer, 0, buffer.Length);
            string content = Encoding.UTF8.GetString(buffer);
            _logger.LogInformation("testsub" + content);
            return Ok(content);
        }

    }
}
